package com.common.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Formatter;

import com.alibaba.fastjson.JSONObject;

import cn.hutool.http.HttpUtil;



/**
 * 请求校验工具类（微信公众号）
 * 
 * @author liufeng
 * @date 2013-05-18
 */
public class SignUtil {
	// 与接口配置信息中的Token要一致
	private static String token = "winxinHello";// token
	public static String STATE = "geesuntar9853";// 状态
	public static String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=";// 获取token的路径
	public static String APP_ID = "wx0efa5fc8ae8850a4";// appid
	public static String APP_SECRET = "d6beaa20f98ad01c91e2f146dbbecd64";// secret
	public static String APP_SEND_TMP_MESSAGE_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";// secret
	public static String[] TEMPLATES = { 
		"m56dHJKQVXkqQRNaWF85vVmlODaOKYg5kdJrw1DZbsI"//上下车记录提醒
	};

	public static String getSign(String jsapi_ticket, String nonce_str,
			String timestamp, String url) {
		// 将token、timestamp、nonce三个参数进行字典序排序
		String string1 = "jsapi_ticket=" + jsapi_ticket + "&noncestr="
				+ nonce_str + "&timestamp=" + timestamp + "&url=" + url;
		String signature = null;
		try {
			MessageDigest crypt = MessageDigest.getInstance("SHA-1");
			crypt.reset();
			crypt.update(string1.getBytes("UTF-8"));
			signature = byteToHex(crypt.digest());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		// 将sha1加密后的字符串可与signature对比，标识该请求来源于微信
		return signature.toLowerCase();
	}
	private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash)
        {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }
	/**
	 * 验证签名
	 * 
	 * @param signature
	 * @param timestamp
	 * @param nonce
	 * @return
	 */
	public static boolean checkSignature(String signature, String timestamp,
			String nonce) {
		String[] arr = new String[] { token, timestamp, nonce };
		// 将token、timestamp、nonce三个参数进行字典序排序
		Arrays.sort(arr);
		StringBuilder content = new StringBuilder();
		for (int i = 0; i < arr.length; i++) {
			content.append(arr[i]);
		}
		MessageDigest md = null;
		String tmpStr = null;

		try {
			md = MessageDigest.getInstance("SHA-1");
			// 将三个参数字符串拼接成一个字符串进行sha1加密
			byte[] digest = md.digest(content.toString().getBytes());
			tmpStr = byteToStr(digest);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		content = null;
		// 将sha1加密后的字符串可与signature对比，标识该请求来源于微信
		return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;
	}
	
	public static String getOpenId(String code){
//		String code="061bygWg2ZPd0J0FWbXg29LiWg2bygWs";
		String openid = "";
		try {
			String url = SignUtil.ACCESS_TOKEN_URL+SignUtil.APP_ID+"&secret="+SignUtil.APP_SECRET+"&code="+code+"&grant_type=authorization_code";
			String jsonStr = HttpUtil.get(url);
			openid = JSONObject.parseObject(jsonStr).getString("openid");
		} catch (Exception e) {
			// TODO: handle exception
		}
        return openid;
	}
	

//	public static void main(String[] args) {
//		String openid=SignUtil.getOpenId("001lif1p1OvJrj0xYg1p1iUl1p1lif1w");
//		System.out.println(openid);//oEZA15-7X9BM5F25Gv18sNvVhAx4
////		new UploadService().sendBusMessage("2019-09-20 16:00", "段登明", openid, "布吉天虹附近", "上车", "http://geesuntar.cn/CloudServices/upload/photo/jzjz/430224199106112215.jpg");
//	}

	/**
	 * 将字节数组转换为十六进制字符串
	 * 
	 * @param byteArray
	 * @return
	 */
	private static String byteToStr(byte[] byteArray) {
		String strDigest = "";
		for (int i = 0; i < byteArray.length; i++) {
			strDigest += byteToHexStr(byteArray[i]);
		}
		return strDigest;
	}

	/**
	 * 将字节转换为十六进制字符串
	 * 
	 * @param mByte
	 * @return
	 */
	private static String byteToHexStr(byte mByte) {
		char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
				'B', 'C', 'D', 'E', 'F' };
		char[] tempArr = new char[2];
		tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
		tempArr[1] = Digit[mByte & 0X0F];

		String s = new String(tempArr);
		return s;
	}
}